#!/usr/bin/perl 
#
#

use lib qw(../lib);

use strict;
use warnings;


use Data::Dumper;
use DBI;

use MTT::Libs::Masks;


my $dbh = DBI->connect(
	'dbi:mysql:database=mtt',
	'root',
	'a1s3an',
	{
		RaiseError => 1
	}
) || die DBI->errstr;

$dbh->do('SET NAMES utf8');

my $masks = MTT::Libs::Masks->new(dbh => $dbh);

my %cols = (
	strom => {
		out => 'a_number',
		in	=> 'b_number',
		indexies => [ qw(a_mask b_mask trunk_in trunk_out switch start_time time_answer end_time) ]
	},
	voip => {
		out => 'Calling_Station_Id_31',
		in	=> 'Called_Station_Id_30',
		indexies => [ qw(a_mask b_mask switch ) ]
	},
	ewsd => {
		out => 'trunk_out_number',
		in	=> 'trunk_in_number',
		indexies => [ qw(a_mask b_mask trunk_in trunk_out switch start_time answer_time end_time
						trunk_in_name trunk_out_name) ]
	}
);

my %tables;
foreach  ( @{ $dbh->selectall_arrayref('SHOW TABLES') } ) {
	next unless $_->[0] =~ /^(.*?)_?\d{4}_\d\d_\d\d$/;
	push @{ $tables{ $1 ? $1 : 'strom'} }, $_->[0];
}


open(LOG, '>', 'add_masks.log');

eval {
	foreach my $t_type ( keys %tables ) {
		foreach my $table ( @{ $tables{$t_type} } ) {

			my $tt = $dbh->selectrow_arrayref("SHOW CREATE TABLE $table")->[1];

			$dbh->do("ALTER TABLE $table ADD a_mask varchar(13)") unless $tt =~ /a_mask/;
			print LOG "Add a_mask to $table\n";
			print "Add b_mask to $table\n";

			$dbh->do("ALTER TABLE $table ADD b_mask varchar(13)") unless $tt =~ /b_mask/;
			print LOG "Add a_mask to $table\n";
			print "Add a_mask to $table\n";


			foreach my $index ( @{ $cols{$t_type}->{indexies} } ) {
				
				my $index_name = "key_$index";
				if ( $tt =~ /$index_name/ ) {
					next;
					$dbh->do("DROP INDEX $index_name ON $table");
				}
#				next; Раскоментировать для удаления индексов и пропуска всего остального

				$dbh->do("ALTER TABLE $table ADD INDEX $index_name($index)");
				print LOG "Add index $index_name($index) to $table\n";
				print "Add index $index_name($index) to $table\n";
			}

			my $sth = $dbh->prepare("UPDATE $table SET b_mask = ?, a_mask = ? WHERE id = ?");
			my $i = 0;
			print LOG "Update masks column for $table...\n";
			print "Update masks column for $table...\n";
			foreach my $row ( @{ $dbh->selectall_arrayref("SELECT id, $cols{$t_type}->{out}, $cols{$t_type}->{in} FROM $table") } ) {
				my ($b_mask, $a_mask) = ( $masks->get_mask( $row->[1] ) || '', $masks->get_mask( $row->[2] ) || '' );

				unless ($a_mask && $b_mask) {
					my $s = "not found mask for" . ( !$b_mask ? " a_number: $row->[1];" : '') . ( !$a_mask ? " b_number: $row->[2];" : '' ) . "\n";
					print LOG $s;
					print $s;
				}

				my $rs = $sth->execute($b_mask, $a_mask, $row->[0]);
				$i++ if $rs;
			}

			print LOG "Update $i columns successfully\n";
			print "Update $i columns successfully\n";
		}
	}
};

if ($@) {
	print LOG $@;
}

close LOG;






